#include <string>
#include <map>
#include "Clippy.h"
#include "Storage.h"
Storage * Storage::instance_ = NULL;

bool Storage::empty(string *s){
	if (s == NULL) {
		return 1;
	}
	if ( s->length() < 1) {
		return 1;
	}
	return 0;
}

void Storage::replace(string ** target, string * source) {
	if (*target != NULL) {
		delete *target;
	}
	*target = new string(*source);
}

void Storage::updateValue(Atom atom, string *ownerName, string *newValue) {
	//printf("update1?\n");
	if (empty(newValue)) {
		return;
	}
	//printf("update2?\n");
	if (empty(ownerName)) {
		return;
	}
	//printf("update3?\n");
	if (!passFilter(atom, ownerName)) {
		return;
	}
	//printf("updateing %lu %s %s \n",atom,ownerName->c_str(), newValue->c_str());
	string *old = values_.get(atom);
	if (!empty(old)) {
		if (old->compare(*newValue) == 0) {
			return;
		}
	}
	values_.put(atom, new std::string(*newValue));
	if (newValue->compare(*value_.get()) == 0) {
		return;
	}
	//std::cout << "'" << this->value_.get() <<"'='" << newValue <<std::endl;
	value_.reset(new std::string(*newValue));
}

void Storage::setFilterString(Atom atom, string* re) {
	
	if (!empty(re)) {
		filters_.put(atom, new Regex(re));
	} else {
		filters_.erase(atom);
	}
}
bool Storage::passFilter(Atom atom,  string* ownerName){
	Regex* regex = filters_.get(atom);
	if (regex == NULL) {
		return 1;
	}
	return regex->match(ownerName);
}

